package com.example.helpconnect;

import java.util.Arrays;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.example.controller.LocationObtainer;
import com.example.controller.User;
import com.example.model.UserCRUD;
import com.facebook.GraphUser;
import com.facebook.LoggingBehaviors;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
//import com.facebook.samples.sessionlogin.R;
//import com.facebook.samples.sessionlogin.SessionLoginSampleActivity.SessionStatusCallback;

public class LoggingActivity extends Activity {
	
	static String currentLocation = new String();
	static Double latitude = 0.0;
	static Double longitude = 0.0;
	static LocationObtainer locTool;

	static final String URL_PREFIX_FRIENDS = "https://graph.facebook.com/me/friends?access_token=";
    TextView textInstructionsOrLink;
    Button buttonLoginLogout;
    Session.StatusCallback statusCallback = new SessionStatusCallback();
    

    
	@Override
    public void onCreate(Bundle savedInstanceState) {
    	
    	//Add these two lines to disable StrictMode
    	StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    	StrictMode.setThreadPolicy(policy); 
        
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.logging);
        buttonLoginLogout = (Button)findViewById(R.id.buttonLoginLogout);
        textInstructionsOrLink = (TextView)findViewById(R.id.instructionsOrLink);

        LocationManager gpsLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		LocationManager networkLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locTool = new LocationObtainer(gpsLocationManager, networkLocationManager);
        
        Settings.addLoggingBehavior(LoggingBehaviors.INCLUDE_ACCESS_TOKENS);
        
        Session session = Session.getActiveSession();
        if (session == null) {
            if (savedInstanceState != null) {
                session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
            }
            if (session == null) {
                session = new Session(this);
            }
            Session.setActiveSession(session);
            if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
                session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
            }
        }

        updateView();
    }

    @Override
    public void onStart() {
        super.onStart();
        Session.getActiveSession().addCallback(statusCallback);
    }
    
   

    @Override
    public void onStop() {
        super.onStop();
        Session.getActiveSession().removeCallback(statusCallback);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Session session = Session.getActiveSession();
        Session.saveSession(session, outState);
    }

    private void updateView() {
        Session session = Session.getActiveSession();
        if (session.isOpened()) {
            textInstructionsOrLink.setText("Welcome to HelpConnect!");
            buttonLoginLogout.setText(R.string.logout);
            buttonLoginLogout.setOnClickListener(new OnClickListener() {
                public void onClick(View view) { onClickLogout(); }
            });
            
            Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
    	        // callback after Graph API response with user object
            	// This allows us to retrieve the current user's information to store in the database
    	        
            	@Override
    	        public void onCompleted(GraphUser user, Response response) {
    	          if (user != null) {
    	        	  
    	            //TextView welcome = (TextView) findViewById(R.id.welcome);  	            
    	            
    	            //Location userLocation = (Location) user.getProperty("user_location");
    	            //userLocation.toString();
    	        	  
					//LocationManager gpsLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
					//LocationManager networkLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
					//LocationObtainer locTool = new LocationObtainer(gpsLocationManager, networkLocationManager);
					Location loc = locTool.getCurrentLocation();
					currentLocation = loc.getLatitude() + ", " + loc.getLongitude();
					latitude = locTool.getLatitude();
					longitude = locTool.getLongitude();
					
					textInstructionsOrLink.setText("Hello " + user.getName() + "!");    	            		
    	            /*
    	            textInstructionsOrLink.setText("Hello " + user.getName() + "!\nYour unique Facebook user ID is " + user.getId() +
    	            		"\nYour facebook email address is " + user.getProperty("email") + "\nYour Location is: "+ currentLocation);
    	            		//"\nYour location is " + userLocation.toString());
    	            		 
    	             */
    	            User newUser = new User(new UserCRUD());
    	            
    	            newUser = newUser.read(Integer.parseInt(user.getId()));
    	            
    	            if(newUser != null)
    	            {
    	            	newUser.setLatitude(latitude);
    	            	newUser.setLongitude(longitude);
    	            	
    	            	newUser.update();
    	            	
    	            }
    	            else{
    	            	//textInstructionsOrLink.setText("You are being created in the database.\n Location: " + currentLocation);
    	            	//textInstructionsOrLink.setText("Longitude: " + longitude.toString() + "\nLatitude: " + latitude.toString());
    	            	newUser = new User(new UserCRUD());
    	            	
    	            	newUser.setUserID(Integer.parseInt(user.getId()));
    	            	newUser.setFirstName(user.getFirstName());
    	            	newUser.setLastName(user.getLastName());
    	            	newUser.setLatitude(latitude);
    	            	newUser.setLongitude(longitude);
    	            	
    	            	TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); 
    	            	String number = tm.getLine1Number();
    	            	
    	            	newUser.setPhone(number);
    	            	newUser.setEmail((String)user.getProperty("email"));
    	            	
    	            	newUser.create();
    	            	
    	            	
    	            }
    	            
    	            Intent homePage = new Intent(getApplicationContext(), HomePageActivity.class);
    	            homePage.putExtra("userID", newUser.getUserID());    	            
    	            startActivity(homePage);
    	            finish();
    	            
    	          }
    	        }

				
    	      });
    	      Request.executeBatchAsync(request);
            
        } else {
            textInstructionsOrLink.setText(R.string.instructions);
            buttonLoginLogout.setText(R.string.login);
            buttonLoginLogout.setOnClickListener(new OnClickListener() {
                public void onClick(View view) { onClickLogin(); }
            });
        }
    }

    private void onClickLogin() {
        Session session = Session.getActiveSession();
        if (!session.isOpened() && !session.isClosed()) {
            session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback).setPermissions(Arrays.asList("email")));
        } else {
            Session.openActiveSession(this, true, statusCallback);
        }
    }

    private void onClickLogout() {
        Session session = Session.getActiveSession();
        if (!session.isClosed()) {
            session.closeAndClearTokenInformation();
        }
    }

    private class SessionStatusCallback implements Session.StatusCallback {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
            updateView();
        }
    }
	
}
